﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;

namespace CCPSIP.PC
{
    /// <summary>PC版iSender登入API(還未使用)</summary>
    public class login : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string cid = req.Form["Cid"];
                string pc_info = req.Form["PCInfo"];

                //【02】驗證身分
                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                    throw new Exception("ERROR_01: Cannot identify this device");//無法識別此裝置

                //【03】使用者上線
                if (!PCKit.IsLogedin(userInfo.SIP_Num))  //若使用者不在線上
                    PCKit.InsertLoginData(userInfo.SIP_Num, cid);
                else
                    throw new Exception("ERROR_02: The user has logged in.");  //使用者已在線上

                //【04】記錄Log

                //【99】回傳結果
                LoginStatus ReturnStatus = new LoginStatus(userInfo.SIP_Num, DateTime.Now.ToString());
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(ReturnStatus);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}